package com.bjb.vr.auth.filter;

import com.bjb.vr.auth.exception.RefreshTokenNotMatchException;
import com.bjb.vr.common.utils.RedisUtil;
import com.bjb.vr.common.constant.TokenConstants;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.websocket.AuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 自定义退出登录处理器
 *
 * @version 1.0.0
 * @author: HuJingBo
 * @time: 2022/4/12 11:53
 */

@Slf4j
public class CustomLogoutHandler implements LogoutHandler {

    private final static String REFRESH_TOKEN_PARAMETER = "refreshTokenId";

    private final RedisUtil redisUtil;

    public CustomLogoutHandler(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    @SneakyThrows
    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        // 判断请求参数是否为空
        int available = request.getInputStream().available();
        if (available == 1) {
            // 获取请求参数
            Map<String, String> parameters = new ObjectMapper().readValue(request.getInputStream(), Map.class);
            String refreshTokenId = parameters.get(REFRESH_TOKEN_PARAMETER);
            if (StringUtils.isEmpty(refreshTokenId)) {
                throw new RefreshTokenNotMatchException("refreshTokenId不能为空");
            }
            // 删除redis中的refreshToken
            redisUtil.del(TokenConstants.LOGIN_TOKEN_KEY + refreshTokenId);
        }
    }
}
